package com.huawei.esdk.tp.healthcare.local.impl.service;

import javax.xml.ws.Holder;

import com.huawei.esdk.tp.healthcare.local.authentication.AuthorizeService;
import com.huawei.esdk.tp.healthcare.local.impl.autogen.TPCommon;
import com.huawei.esdk.tp.healthcare.local.impl.utils.Base64Utils;
import com.huawei.esdk.tp.healthcare.local.impl.utils.ClientProvider;
import com.huawei.esdk.tp.healthcare.local.impl.utils.Encrypt;
import com.huawei.esdk.tp.healthcare.local.impl.utils.ExceptionUtils;

public class AuthorizeServiceImpl implements AuthorizeService {
	private TPCommon tPCommonClient = ((TPCommon) ClientProvider
			.getClient(TPCommon.class));
	
	private static AuthorizeServiceImpl instance = null;

	public static synchronized AuthorizeServiceImpl getInstance() {
		if (null == instance) {
			instance = new AuthorizeServiceImpl();
		}
		return instance;
	}

	
	public Integer login(String userName, String password) {
	    
		Holder<Integer> sdkResponse = new Holder<Integer>();
		Holder<byte[]> randomSequence = new Holder<byte[]>();
		Holder<String> hashType = new Holder<String>();

		try {
			tPCommonClient.loginRequest(userName, "API", 2, sdkResponse,
					randomSequence, hashType);
			if (sdkResponse.value.intValue() == 0) {
				String encodePwd = Base64Utils.encode(randomSequence.value);
				String pwd = Encrypt.getEncryptPassword(null == encodePwd ? ""
						: encodePwd, password);
				byte[] base64Pwd = Base64Utils.getFromBASE64(null == pwd ? ""
						: pwd);
				return tPCommonClient
						.authenticate(null == base64Pwd ? new byte[0]
								: base64Pwd);
			}
		} catch (Exception e) {
			return ExceptionUtils.processSoapException(e);
		}
		return sdkResponse.value;
	}

	
	public Integer logout() {
		try {
			return tPCommonClient.logout();
		} catch (Exception e) {
			return ExceptionUtils.processSoapException(e);
		}
	}

	
	public Integer keepAlive() {
		try {
			return tPCommonClient.keepAlive();
		} catch (Exception e) {
			return ExceptionUtils.processSoapException(e);
		}
	}

}
